package swimv2.session;
import java.util.Calendar;
import java.util.Date;

import java.util.List;
import java.util.regex.*;


import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.resource.spi.IllegalStateException;

import org.jboss.ejb3.annotation.RemoteBinding;

import swimv2.entity.*;
import swimv2.session.*;

/**
 * Session Bean implementation class LoginBean
 */
@Stateful
@RemoteBinding( jndiBinding = "ILoginRemote" )
public class LoginBean implements ILoginRemote {
	@PersistenceContext(unitName = "swimv2")
	protected EntityManager manager;
	private Integer id_utente;
	private String nome_utente;
	private boolean logged=false;

    /**
     * Default constructor. 
     */
    public LoginBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public boolean CreateUser(String name, String surname, String username,
			String psw, String email, String dataNascita) throws IllegalStateException {
		
		User u= new User();
		u.setName(name);
		u.setUsername(username);
		u.setPassword(psw);
		u.setSurname(surname);
		u.setMail(email);
		u.setPassword(psw);
		
		Query q = manager.createQuery("SELECT v FROM View v WHERE v.name = :name")
						.setParameter("name", "registered");
		
		List<View> v = (List<View>)q.getResultList();
		
		if (v.size()!=1)
		{
			throw new IllegalStateException("View not present in DB");
		}
		
		u.setView(v.get(0));
		
		
		manager.persist(u);
		return true;
	}
	
	@Override
	public boolean LoginUser(String username, String psw) throws IllegalStateException {
		
		Query q = manager.createQuery("SELECT u FROM User u WHERE u.password = :psw and u.name= :n");
		q.setParameter( "psw", psw );
		q.setParameter( "n", username );
		List<User> u = (List<User>)q.getResultList();
		
		if(u.size()!=1)
		{
			if(this.logged==true)
			{
				throw new IllegalStateException();
			}
			this.logged=false;
			return false;
		}
		else 
		{
			id_utente= u.get(0).getId();
			
			this.logged=true;
			return true;
		}
	}

	@Override
	public User getLoggedUser() {
		if(!this.logged)
		{	return null; }
		else
		{
			Query q = manager.createQuery("SELECT u FROM User u WHERE u.id = :id");
			q.setParameter( "id", id_utente );
			User r = (User)q.getSingleResult();
			return r;
		}
	}

	@Override
	public void LogOut() {
		id_utente=null;
		logged=false;
		nome_utente=null;		
	}
	
	private boolean validEmail(String email){
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		//Eseguiamo il match della stringa data con il pattern
		Matcher m = p.matcher(email);
		//Salviamo il risultato del match
		boolean matchFound = m.matches();
		if(matchFound){
			return true;
		}
		else return false;
	};
	
	private boolean validBDay(String data){
		boolean controller=true;
		Calendar cal = Calendar.getInstance();
		String[] items = data.split("/");
		//giorno
		if(Integer.getInteger(items[0])<32 && Integer.getInteger(items[0])>0) {}
		else return false;
		//mese
		if(Integer.getInteger(items[1])<13 && Integer.getInteger(items[1])>0) {}
		else return false;
		//anno
		if(Integer.getInteger(items[2])<cal.get(Calendar.YEAR)) {}
		else return false;
		return controller;
	}
	
	private boolean UserExist(Integer id_utente){
		Query q = manager.createQuery("SELECT u FROM user u WHERE u.id = :id");
		q.setParameter( "id", id_utente );	
		User u=(User)q.getSingleResult();
		if(u!=null){
			return true;
		}
		else return false;
	}

	@Override
	public void ModifyUser(User u) {
		manager.persist(u);
	}
	
}
